package com.greenhouse.service.impl;

import com.greenhouse.mapper.environment.EnvironmentMapper;
import com.greenhouse.mapper.environment.EquipmentMapper;
import com.greenhouse.mapper.glogs.AlertsMapper;
import com.greenhouse.mapper.glogs.LogsMapper;
import com.greenhouse.mapper.greenhouse.UserMapper;
import com.greenhouse.model.User;
import com.greenhouse.service.UserService;
import com.greenhouse.utily.ConstantUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogsMapper logsMapper;
    @Autowired
    private AlertsMapper alertsMapper;
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public User insertUser() {
        User u = new User();
        u.setUsername(String.valueOf(ConstantUtils.USERNAME_START + userMapper.getMaxId()));
        u.setPassword(bCryptPasswordEncoder.encode("123456"));
        u.setName("user");
        u.setRole(1);
        userMapper.insertUser(u);
        u = userMapper.findByUsername(u.getUsername());
        //创建用户日志表
        logsMapper.createGreanhouserEnvironment("l_" + u.getId());
        //创建用户预警表
        alertsMapper.createAlerts("a_" + u.getId());
        //创建用户设备表
        equipmentMapper.createUserEquipment("e_" + u.getId());

        return userMapper.findByUsername(u.getUsername());
    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user != null) {
            if (bCryptPasswordEncoder.matches(password, user.getPassword())) {
                user.setPassword(null);
                return user;
            }
        }
        return null;
    }

    @Override
    public Integer deleteUser(Integer id) {
        //删除用户
        return userMapper.deleteUser(id);
    }

    @Override
    public Integer updatePassword(String password, Integer id) {
        password = bCryptPasswordEncoder.encode(password);
        return userMapper.updatePassword(password, id);
    }

    @Override
    public Integer updateName(String name, Integer id) {
        return userMapper.updateName(name, id);
    }

    @Override
    public Integer updateEmail(String email, Integer id) {
        return userMapper.updateEmail(email, id);
    }

    @Override
    public Integer updateHeadImg(String headImgUrl, Integer id) {
        return userMapper.updateHeadImg(headImgUrl,id);
    }
}
